<template>
  <div class="app-container">
    <el-form  class="query-wrapper" :model="queryParams" inline>
      <el-form-item prop="countryCode">
        <el-input v-model="queryParams.countryCode" style="width: 180px" placeholder="Country Code" clearable />
      </el-form-item>
      <el-form-item prop="countryName">
        <el-input v-model="queryParams.countryName" style="width: 180px" placeholder="Country Name" clearable />
      </el-form-item>
      <el-form-item>      
        <el-button type="primary" icon="search" v-hasPermi="['country:get']" @click="search">{{
          $t("ship.button.search")
          }}</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
        <el-button type="primary"  plain icon="Plus" @click="addClickEvent" v-hasPermi="['country:add']">
          {{ $t("ship.button.plus") }}
        </el-button>
        <!-- <el-button type="primary" icon="upload" onclick="this.nextSibling.click()">Import</el-button> -->
        <input id="upload-spec-file" type="file" accept=".xlsx" v-show="false" @change="uploadFile($event)"
          v-hasPermi="['country:upload']" />
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <el-button type="warning" plain icon="download" v-hasPermi="['country:export']" @click="handleExport">Export</el-button>
      </el-form-item>
    </el-form>
  </div>

  <el-table stripe class="daf-table" :data="listData" style="width: 100%" @sort-change="handleSortChange">
    <el-table-column prop="countryCode" label="Country Code" />
    <el-table-column prop="countryName" label="Country Name" sortable />
    <el-table-column prop="chineseName" label="Chinese Name" />
    <el-table-column prop="areaCode" label="Area Code" />
    <el-table-column label="Operation" v-hasPermi="['country:edit']">
      <template #default="scope">
        <span class="btn-primary" @click="editClickEvent(scope.row)">{{
          $t("ship.button.edit")
          }}</span>&nbsp;&nbsp;
        <span class="btn-primary" @click="removeClickEvent(scope.row.countryId)">{{
          $t("ship.button.remove")
          }}</span>
      </template>
    </el-table-column>
  </el-table>

  <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
    @pagination="pageQuery" style="float: right" />

  <el-dialog :width="500" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="24">
          <el-form-item label="Country Code" label-width="120px" prop="countryCode" required>
            <el-input v-model="formParam.countryCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Country Name" label-width="120px" prop="countryName" required>
            <el-input v-model="formParam.countryName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Chinese Name" label-width="120px" prop="chineseName" required>
            <el-input v-model="formParam.chineseName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Area Code" label-width="120px" prop="areaCode">
            <el-input v-model="formParam.areaCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
          }}</el-button>
        <el-button @click="resetForm" type="warning">{{
          $t("ship.button.reset")
          }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
          }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup name="country">
  import { ref, onMounted, reactive } from "vue";
  import service from "@/utils/request";
  import { downloadFile } from "@/utils/downloadFile";
  import { ElNotification, ElMessageBox } from "element-plus";
  import SearchReset from '@/components/SearchReset/index.vue'

  const custForm = ref(null);
  const dialogTitle = ref("");
  const initForm = {
    countryId: null,
    countryName: null,
    countryCode: null,
    chineseName: null,
    areaCode: null
  };
  const formParam = reactive(Object.assign({}, initForm));

  const total = ref(0);

  const rules = ref({});

  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    countryCode: null,
    countryName: null,
    orderByColumn: undefined,
    isAsc: undefined,
  });

  const listData = ref([]);
  const refreshTable = async () => {
    let result = await service.get("/shipping/country/getTable", { params: queryParams });
    listData.value = result.data;
    total.value = result.total;
  };
  // let searchParams = toRefs(queryParams)
  const resetQuery = (data) => {
    Object.assign(queryParams, data)
    refreshTable()
  }
  const dialogFormVisible = ref(false);

  const editClickEvent = (row: any) => {
    dialogTitle.value = "Update Country";
    dialogFormVisible.value = true;
    isAdd = false;
    Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
  };

  let isAdd = false;

  const addClickEvent = () => {
    dialogTitle.value = "Add country";
    isAdd = true;
    dialogFormVisible.value = true;
    Object.assign(formParam, initForm);
  };

  const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
  };

  const submitForm = () => {
    // @ts-ignore
    custForm.value.validate(async (valid) => {
      if (!valid) {
        return;
      }

      await service[isAdd ? "post" : "put"]("shipping/country", formParam);
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "save successful!",
        position: "bottom-right",
      });
      dialogFormVisible.value = false;
      refreshTable();
    });
  };

  const pageQuery = async (e) => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };

  const search = () => {
    refreshTable();
  };

  const sleep = (ms) => {
    return new Promise((resolve) => setTimeout(resolve, ms));
  };

  const uploadFile = async (event) => {
    if (event.target == null || event.target.files[0] == null) {
      return;
    }
    const formData = new FormData();
    formData.append("file", event.target.files[0]);
    await service["post"]("shipping/country/uploadFile", formData);
  };

  const handleSortChange = async (column: any) => {
    queryParams.orderByColumn = column.prop;
    queryParams.isAsc = column.order; //动态取值排序顺序
    refreshTable();
  };

  const removeClickEvent = (id) => {
    ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }).then(async () => {
      await service.delete(`shipping/country/${id}`);

      refreshTable();
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "Delete successfully!",
        position: "bottom-right",
      });
    });
  };

  const handleExport = (row: any) => {
    downloadFile("/shipping/country/export", queryParams, `country.xlsx`);
  }

  onMounted(async () => {
    refreshTable();
  });
</script>
<style lang="scss" scoped>
  ::v-deep.el-table td.el-table__cell div {
    text-align: center;
  }

  .el-table__expand-column .cell {
    display: none;
  }

  .c-expand {
    color: #888;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    cursor: pointer;
    width: 100%;
    height: 100%;
  }

  .c-expand i {
    font-size: 16px;
  }

  .c-expand i.expand {
    font-size: 16px;
    transform: rotate(90deg);
    transition: all 0.25s;
  }
</style>